package com.gzhryc.shared_device.oem.h5.agent.controllers.api.v1.cdcz;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.NumberTools;
import com.gzhryc.common.StringTools;
import com.gzhryc.common.api.DefaultAPIResponse;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.cdcz.code.CDCZCostConfig;
import com.gzhryc.shared_device.cdcz.code.dao.db.CDCZFeeTemplate;
import com.gzhryc.shared_device.cdcz.code.dao.models.CDCZPowerIntervalMoneyContent;
import com.gzhryc.shared_device.cdcz.code.services.CDCZFeeTemplateService;
import com.gzhryc.shared_device.oem.code.ConfigUtils;
import com.gzhryc.shared_device.oem.code.business.EBusinessType;
import com.gzhryc.shared_device.oem.code.place.services.PlaceBusinessConfigService;
import com.gzhryc.shared_device.oem.code.user.ERoleType;
import com.gzhryc.shared_device.oem.h5.agent.ClientAPICodeConstants;
import com.gzhryc.shared_device.oem.h5.agent.LoginUser;
import com.gzhryc.shared_device.oem.h5.agent.WebConstants;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.cdcz.CDCZFeeTemplateDelRequest;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.cdcz.CDCZFeeTemplateListResponse;
import com.gzhryc.shared_device.oem.h5.agent.dto.api.v1.cdcz.CDCZFeeTemplateSaveRequest;

public class CDCZFeeTemplateController {

    @Route(value = "/agent/api/v1/cdcz/fee_template/list.data")
    public CDCZFeeTemplateListResponse list(HttpServletRequest request) {
        CDCZFeeTemplateListResponse apiResp = new CDCZFeeTemplateListResponse(ClientAPICodeConstants.NULL_DATA, "暂无数据");
        LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
        if (loginUser != null) {
            List<CDCZFeeTemplate> feeTemplateList = null;
            if(ERoleType.Agent.index().equals(loginUser.getRoleType())){
                feeTemplateList = CDCZFeeTemplateService.self().findByUserId(loginUser.getId());
            }else if(ERoleType.Partner.index().equals(loginUser.getRoleType())){
                feeTemplateList = CDCZFeeTemplateService.self().findByUserId(loginUser.getParentId());
            }

            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
            apiResp.getBody().setItems(new ArrayList<>());

            //全局
            CDCZCostConfig config = ConfigUtils.getCDCZCostConfig();
            CDCZFeeTemplateListResponse.Item item = new CDCZFeeTemplateListResponse.Item();
            item.setTitle("全局模版");
            item.setMinWalletPrice(config.getMinWalletMoneyStr());
            item.setMaxChargeTimesMinute(config.getMaxTimesMinute());
            item.setMaxChargeElectricity(config.getMaxChargeElectricity());
            if (StringTools.isNotBlank(config.getTimeSetMeal())) {
                item.setTimeSetMeal(Arrays.asList(config.getTimeSetMeal().split(",")));
            }
            if (StringTools.isNotBlank(config.getPimContent())) {
                CDCZPowerIntervalMoneyContent content = JsonTools.fromJson(config.getPimContent(), CDCZPowerIntervalMoneyContent.class);
                item.setPimItems(new ArrayList<>());
                for (CDCZPowerIntervalMoneyContent.Item temp : content.getItems()) {
                    CDCZFeeTemplateListResponse.PimItem pimItem = new CDCZFeeTemplateListResponse.PimItem();
                    pimItem.setMinPower(temp.getMinPower());
                    pimItem.setMaxPower(temp.getMaxPower());
                    pimItem.setPrice(temp.getMoneyStr());
                    item.getPimItems().add(pimItem);
                }
            }
            apiResp.getBody().getItems().add(item);

            if(feeTemplateList != null && feeTemplateList.size() > 0){
                for(CDCZFeeTemplate feeTemplate : feeTemplateList){
                    item = new CDCZFeeTemplateListResponse.Item();
                    item.setId(feeTemplate.getId());
                    item.setTitle(feeTemplate.getTitle());
                    item.setMaxChargeElectricity(feeTemplate.getMaxChargeElectricity());
                    item.setMaxChargeTimesMinute(feeTemplate.getMaxChargeTimesMinute());
                    item.setMinWalletPrice(feeTemplate.getMinWalletMoneyStr());
                    if(StringTools.isNotBlank(feeTemplate.getTimeSetMeal())){
                        item.setTimeSetMeal(Arrays.asList(feeTemplate.getTimeSetMeal().split(",")));
                    }
                    if(StringTools.isNotBlank(feeTemplate.getPimContent())) {
                        CDCZPowerIntervalMoneyContent content = JsonTools.fromJson(feeTemplate.getPimContent(),CDCZPowerIntervalMoneyContent.class);
                        item.setPimItems(new ArrayList<>());
                        for(CDCZPowerIntervalMoneyContent.Item temp : content.getItems()) {
                            CDCZFeeTemplateListResponse.PimItem pimItem = new CDCZFeeTemplateListResponse.PimItem();
                            pimItem.setMinPower(temp.getMinPower());
                            pimItem.setMaxPower(temp.getMaxPower());
                            pimItem.setPrice(temp.getMoneyStr());
                            item.getPimItems().add(pimItem);
                        }
                    }
                    apiResp.getBody().getItems().add(item);
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/cdcz/fee_template/save.do")
    public DefaultAPIResponse save(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "保存收费模版失败");
        CDCZFeeTemplateSaveRequest apiReq = WebUtils.getJsonRequest(request, CDCZFeeTemplateSaveRequest.class);
        if (apiReq != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser != null) {
                Long userId = loginUser.getId();
                if(!ERoleType.Agent.index().equals(loginUser.getRoleType())){
                    if(ERoleType.Partner.index().equals(loginUser.getRoleType())) {
                        userId = loginUser.getParentId();
                    }else{
                        apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限保存收费模版");
                        return apiResp;
                    }
                }

                if(StringTools.isBlank(apiReq.getBody().getTitle())){
                    apiResp.setMsg("请填写模版标题");
                    return apiResp;
                }
                if(apiReq.getBody().getMinWalletPrice() != null){
                    Integer minWalletMoney = NumberTools.changeMoney(apiReq.getBody().getMinWalletPrice());
                    if(minWalletMoney < 1 || minWalletMoney > 30000){
                        apiResp.setMsg("钱包最低金额设置范围1-300元");
                        return apiResp;
                    }
                }else {
                    apiResp.setMsg("请填写钱包最低金额");
                    return apiResp;
                }

                if(apiReq.getBody().getTimeSetMeal() == null || apiReq.getBody().getTimeSetMeal().size() <= 0){
                    apiResp.setMsg("请填写时间套餐");
                    return apiResp;
                }

                if(apiReq.getBody().getMaxChargeElectricity() != null) {
                    if(apiReq.getBody().getMaxChargeElectricity() < 1 || apiReq.getBody().getMaxChargeElectricity() > 90){
                        apiResp.setMsg("最大充电电量1-90度");
                        return apiResp;
                    }
                }else{
                    apiResp.setMsg("请填写最大充电电量");
                    return apiResp;
                }

                if(apiReq.getBody().getMaxChargeTimesMinute() != null) {
                    if(apiReq.getBody().getMaxChargeTimesMinute() < 1 || apiReq.getBody().getMaxChargeTimesMinute() > 1440){
                        apiResp.setMsg("最大充电时长1-1440分钟");
                        return apiResp;
                    }
                }else{
                    apiResp.setMsg("请填写最大充电时长");
                    return apiResp;
                }

                CDCZFeeTemplate feeTemplate = new CDCZFeeTemplate();
                feeTemplate.setId(apiReq.getBody().getId());
                feeTemplate.setUserId(userId);
                feeTemplate.setTitle(apiReq.getBody().getTitle());
                feeTemplate.setMaxChargeElectricity(apiReq.getBody().getMaxChargeElectricity());
                feeTemplate.setMaxChargeTimesMinute(apiReq.getBody().getMaxChargeTimesMinute());
                feeTemplate.setMinWalletMoney(NumberTools.changeMoneyLi(apiReq.getBody().getMinWalletPrice()));
                feeTemplate.setTimeSetMeal(StringUtils.join(apiReq.getBody().getTimeSetMeal(),","));

                CDCZPowerIntervalMoneyContent content = null;
                if(apiReq.getBody().getPimItems() != null && apiReq.getBody().getPimItems().size() > 0){
                    content = new CDCZPowerIntervalMoneyContent();
                    for(CDCZFeeTemplateSaveRequest.PimItem pimItem : apiReq.getBody().getPimItems()){
                        CDCZPowerIntervalMoneyContent.Item item = new CDCZPowerIntervalMoneyContent.Item();
                        item.setMinPower(pimItem.getMinPower());
                        item.setMaxPower(pimItem.getMaxPower());
                        item.setMoney(NumberTools.changeMoneyLi(pimItem.getPrice()));
                        content.getItems().add(item);
                    }
                    feeTemplate.setPimContent(JsonTools.toJson(content));
                }

                if(feeTemplate.getId() != null) {
                    try {
                        if(CDCZFeeTemplateService.self().updateNotNull(feeTemplate)){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }else{
                    if(StringTools.isBlank(feeTemplate.getPimContent())){
                        feeTemplate.setPimContent(ConfigUtils.getCDCZCostConfig().getPimContent());
                    }
                    try {
                        if(CDCZFeeTemplateService.self().add(feeTemplate)){
                            apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                        }
                    } catch (LogicException e) {
                        apiResp.setMsg(e.getMessage());
                    }
                }
            }
        }
        return apiResp;
    }

    @Route(value = "/agent/api/v1/cdcz/fee_template/del.do")
    public DefaultAPIResponse doDel(HttpServletRequest request) {
        DefaultAPIResponse apiResp = new DefaultAPIResponse(ClientAPICodeConstants.EXECUTE_ERROR, "删除收费模版失败");
        CDCZFeeTemplateDelRequest apiReq = WebUtils.getJsonRequest(request, CDCZFeeTemplateDelRequest.class);
        if (apiReq != null && apiReq.getBody().getId() != null) {
            LoginUser loginUser = WebUtils.getAttribute(request, WebConstants.ATTR_LOGIN_USER, LoginUser.class);
            if (loginUser == null || !ERoleType.Agent.index().equals(loginUser.getRoleType())) {
                apiResp.setCode(ClientAPICodeConstants.NOT_POWER,"无权限删除");
                return apiResp;
            }
            Long total = PlaceBusinessConfigService.self().countByFeeTemplateId(EBusinessType.CDCZ.index(),apiReq.getBody().getId());
            if(total != null && total > 0){
                apiResp.setMsg("该收费模版正在使用，不允许删除");
                return apiResp;
            }

            try {
                if(CDCZFeeTemplateService.self().deleteById(apiReq.getBody().getId())){
                    apiResp.setCode(ClientAPICodeConstants.SUCCESS,null);
                }
            } catch (LogicException e) {
                apiResp.setMsg(e.getMessage());
            }
        }
        return apiResp;
    }
}
